package com.harmontronics.app.pedestal.bridge;

import android.content.Intent;
import android.webkit.JavascriptInterface;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.harmontronics.app.pedestal.agent.WebActivity;
import com.harmontronics.app.pedestal.bridge.model.BaseBridge;

import org.json.JSONObject;

public class WebViewBridge extends BaseBridge {

    private WebActivity activity;

    public WebViewBridge(WebActivity activity) {
        this.activity = activity;
    }

    @JavascriptInterface
    public String open(Object argsJson) {
        LogUtils.d("WEBVIEW.open");
        if (null == argsJson) {
            return fail("参数不能为空", null);
        }

        try {
            JSONObject args = (JSONObject) argsJson;
            LogUtils.d("args: " + args.toString());
            String path = args.getString("path");
            if (path.startsWith("/")) {
                path = path.substring(1);
            }
            Intent intent = new Intent(ActivityUtils.getTopActivity(), WebActivity.class);
            intent.putExtra("url", path);
            ActivityUtils.startActivity(intent);
            return success("open success");
        } catch (Exception e) {
            return fail(e.getMessage(), e);
        }
    }

    @JavascriptInterface
    public String openStart(Object args) {
        LogUtils.d("WEBVIEW.openStart");
        try {
            this.activity.openStart();
            return success("openStart success");
        } catch (Exception e) {
            return fail(e.getMessage(), e);
        }
    }

    @JavascriptInterface
    public void close(Object args) {
        LogUtils.d("WEBVIEW.close");
        this.activity.finish();
    }

    @JavascriptInterface
    public String replace(Object argsJson) {
        LogUtils.d("WEBVIEW.replace");
        if (null == argsJson) {
            return fail("参数不能为空", null);
        }

        try {
            JSONObject args = (JSONObject) argsJson;
            LogUtils.d("args: " + args.toString());
            String path = args.getString("path");
            if (path.startsWith("/")) {
                path = path.substring(1);
            }
            this.activity.replace(path);
            return success("replace success");
        } catch (Exception e) {
            return fail(e.getMessage(), e);
        }
    }

    @JavascriptInterface
    public void onShow(Object args) {
        LogUtils.d("WEBVIEW.onShow");
    }

    @JavascriptInterface
    public void onBack(Object args) {
        LogUtils.d("WEBVIEW.onBack");
    }
}
